//
//  WBUserAccount.swift
//  微博Demo
//
//  Created by 花化华 on 2016/11/24.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
private let userAccountKey = "userAccountKey"

class WBUserAccount: NSObject {

    static let shared = WBUserAccount()
    
    // 令牌
    var access_token: String?
    
    // 令牌有效期
    var expires_in: Double = 0{
        didSet {
            expires_date = Date(timeInterval: expires_in, since: Date())
        }
    }
    var expires_date: Date?
    
    // 用户ID
    var uid: String?
    // 账户昵称
    var screen_name: String?
    // .jpg路径
    var avatar_large: String?
    
    //是否过期
    //return true: 过期了
    var isExpired: Bool {
        return expires_date?.compare(Date()) == .orderedAscending
    }
    
    //是否登录
    var isLogin: Bool {
        return (access_token != nil) && !isExpired
    }
    
    //类的描述信息
    override var description: String {
        return dictionaryWithValues(forKeys: ["access_token", "expires_date", "uid", "screen_name", "avatar_large"]).description
    }
    
    override init() {
        super.init()
         //用kvc的方式,对属性赋值
        if let dict = readUserInfo() {
            setValuesForKeys(dict)
        }
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {}
    
    
    ///  保存用户信息
    ///
    /// - Parameter dict: 从服务器获取的user信息的字典
    func saveUserInfo (dict: [String: Any]) {
        
        //1. 用dict给单例的属性赋值
        setValuesForKeys(dict)
        //2. 模型转字典（对象转字典）
        let userAccountDic = dictionaryWithValues(forKeys: ["access_token", "expires_date", "uid", "screen_name", "avatar_large"])
        //3. 存储用户信息
        UserDefaults.standard.set(userAccountDic, forKey: userAccountKey)
        
    }
    
    
    /// 从沙盒获取存储的用户信息
    ///
    /// - Returns: 用户信息
    func readUserInfo () -> [String: Any]? {
        return UserDefaults.standard.value(forKey: userAccountKey) as? [String: Any]
    }
    
    /// 从沙盒移除存储的用户信息
    func removeUserInfo () {
        UserDefaults.standard.removeObject(forKey: userAccountKey)
    }
    
}
